/* MAKE ARRAY
 * Converts any given file into a C array
 *
 * Usage:
 * ./marray <file> <name>
 */

#include <stdio.h>
#include <string.h>
#include <errno.h>

static void usage (FILE *stream)
{
	fprintf(stream, "Usage:\n");
	fprintf(stream, "./marray <file> <name>\n");
	fprintf(stream, "  <file>  The input file to be converted\n");
	fprintf(stream, "  <name>  The name of the array in the output\n");
}

int main (int argc, char **argv)
{
	FILE *in;
	int c;
	int w;

	/* check usage */
	if (argc != 3) {
		usage(stderr);
		return 1;
	}

	/* open file */
	in = fopen(argv[1], "r");
	if (!in) {
		fprintf(stderr, "error opening %s: %s\n", argv[1], strerror(errno));
		return 1;
	}

	/* output header */
	printf("const char %s[] = {\n ", argv[2]);

	/* read in bytes, and spit them out */
	w = 0;
	while ((c = fgetc(in)) != EOF) {
		printf(" '\\x%02x',", c);
		if (++w == 9) {
			printf("\n ");
			w = 0;
		}
	}

	/* close input */
	fclose(in);

	/* output footer */
	printf(" '\\0'\n};\nconst unsigned int %s_len = sizeof(%s)-1;\n", argv[2], argv[2]);

	return 0;
}
